import { RefObject, useEffect } from 'react'

function useClickOutside(ref: RefObject<HTMLElement>, handler: (event: MouseEvent) => void) {
	useEffect(() => {
		// 监听点击事件
		const listener = (event: MouseEvent) => {
			// 如果点击的是当前元素或者当前元素的子元素，则不执行handler
			if (!ref.current || ref.current.contains(event.target as HTMLElement)) return
			handler(event)
		}
		document.addEventListener('click', listener)
		return () => {
			document.removeEventListener('click', listener)
		}
	}, [ref, handler])
}

export default useClickOutside
